package com.jesse.custom.asyncimageview;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;

import com.jesse.dao.UpdateEvent;
import com.jesse.main.R;
import com.jesse.util.ViewUtil;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.StatFs;
import android.provider.MediaStore;

public class AsyncImageFileUtil {

	public static final int SIZETYPE_B = 1;//获取文件大小单位为B的double值
	public static final int SIZETYPE_KB = 2;//获取文件大小单位为KB的double值
	public static final int SIZETYPE_MB = 3;//获取文件大小单位为MB的double值
	public static final int SIZETYPE_GB = 4;//获取文件大小单位为GB的double值
	
	private AsyncImagePathDefine patchDefine;
	
	public AsyncImageFileUtil(AsyncImagePathDefine patchDefine) {
		this.patchDefine = patchDefine;
	}
	
	/**
	 * 通过Key值获取图片，并指定压缩值，以免大图溢出
	 * 
	 * @param fileKey
	 * @param scaleWidth	
	 * @param scaleHight
	 * @return
	 */
	public Bitmap obtainBitmapBykey(String fileKey, int scaleWidth, int scaleHight) {
		Bitmap bitmap = obtainBitmap(fileKey, scaleWidth, scaleHight); 
		return bitmap;
	}
	
	private Bitmap obtainBitmap (String fileKey, int scaleWidth, int scaleHight) {
		checkPath();
		Bitmap bitmap = AsyncImageLoader.decodeSampledBitmapFromResource(getImageCachePath(fileKey), scaleWidth, scaleHight);
		return bitmap;
	}
	
	/**
	 * 写入缓存文件
	 * @param bitmap
	 * @param imageName
	 */
	public void writeDrawableCacheByName(Bitmap bitmap, String imageName) {
		writeDrawableInSD(bitmap, getImageCachePath(imageName));
	}
	
	/**
	 * 用户下载文件
	 * @param bitmap
	 * @param imageName
	 */
	public void writeDrawableDownloadByName(Bitmap bitmap, String imageName) {
		writeDrawableInSD(bitmap, getImageDownloadPath(imageName));
	}
	
	//TODO 检查图片格式 是 jpeg 或者是png
	public void writeDrawableInSD(Bitmap bitmap, String path) {
		if (bitmap == null) {
			return;
		}
		if(detectCacheFileDir()) {
			checkPath();
			File file = new File(path);
			try {
				if (!file.exists()) { 
					FileOutputStream fOut = new FileOutputStream(file);
					bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
					fOut.flush();
				    fOut.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	/**
	 * 清空缓存区域
	 */
	public void deleteCacheFile() {
		File file=new File(Environment.getExternalStorageDirectory().toString() + patchDefine.getIconFilePath());
		deleteFile(file);
	}
	
	/**
	 * 清空下载区域
	 */
	public void deleteDownloadFile() {
		File file=new File(Environment.getExternalStorageDirectory().toString() + patchDefine.getDownloadPath());
		deleteFile(file);
	}
	
	private void deleteFile(File file) {
		if (file.exists()) { // 判断文件是否存在
			if (file.isFile()) { // 判断是否是文件
				file.delete(); 
			} else if (file.isDirectory()) { //如果它是一个目录
				File files[] = file.listFiles(); 
				for (int i = 0; i < files.length; i++) { 
					this.deleteFile(files[i]); 
				}
			}
			file.delete();
		} else {
			ViewUtil.Toast("文件已清除");
		}
	}
	
	/**
	 * 获取缓存文件大小
	 * @return
	 */
	public void getCacheFilesSize(final UpdateEvent data){
		
		final Handler handler = new Handler() {
			public void handleMessage(Message message) {
				switch (message.what) {
				case 1:
					data.update((String) message.obj);
					break;
				}
			}
		};
		
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				String sizeString = "";
				sizeString = getFileSize(Environment.getExternalStorageDirectory().toString() + patchDefine.getIconFilePath());
				Message.obtain(handler, 1, sizeString).sendToTarget();
			}
		}).start();
	}
	
	/**
	 * 获取下载文件大小
	 * @return
	 */
	public void getDownloadFilesSize(final UpdateEvent data){
		final Handler handler = new Handler() {
			public void handleMessage(Message message) {
				switch (message.what) {
				case 1:
					data.update((String) message.obj);
					break;
				}
			}
		};
		
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				String sizeString = "";
				sizeString = getFileSize(Environment.getExternalStorageDirectory().toString() + patchDefine.getDownloadPath());
				Message.obtain(handler, 1, sizeString).sendToTarget();
			}
		}).start();
	}
	
	private String getFileSize(String path) {
		File file=new File(path);
		long blockSize=0;
		try {
			if(file.isDirectory()){
				blockSize = getFileSizes(file);
			} else{
				blockSize = getFileSize(file);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return FormetFileSize(blockSize);
	}
	/**
	 * 获取单个文件大小
	 * @param file
	 * @return
	 * @throws Exception
	 */
	private long getFileSize(File file) throws Exception {
		long size = 0;
		if (file.exists()){
			FileInputStream fis = null;
			fis = new FileInputStream(file);
			size = fis.available();
			fis.close();
		} 
	
		return size;
	}
	
	/**
	 * 文件夹大小，遍历每个文件的大小
	 * @param f
	 * @return
	 * @throws Exception
	 */
	private long getFileSizes(File f) throws Exception {
		long size = 0;
		File flist[] = f.listFiles();
		for (int i = 0; i < flist.length; i++){
			if (flist[i].isDirectory()){
				size = size + getFileSizes(flist[i]);
			} else{
				size =size + getFileSize(flist[i]);
			}
		}
		return size;
	}
	
	private String FormetFileSize(long fileS) {
		DecimalFormat df = new DecimalFormat("#.00");
		String fileSizeString = "";
		String wrongSize="0B";
		if(fileS==0){
			return wrongSize;
		}
		if (fileS < 1024){
			fileSizeString = df.format((double) fileS) + "B";
		} else if (fileS < 1048576){
			fileSizeString = df.format((double) fileS / 1024) + "KB";
		} else if (fileS < 1073741824){
			fileSizeString = df.format((double) fileS / 1048576) + "MB";
		} else{
			fileSizeString = df.format((double) fileS / 1073741824) + "GB";
		}
		return fileSizeString;
	}
	
	private double FormetFileSize(long fileS,int sizeType) {
		DecimalFormat df = new DecimalFormat("#.00");
		double fileSizeLong = 0;
		switch (sizeType) {
			case SIZETYPE_B:
				fileSizeLong=Double.valueOf(df.format((double) fileS));
			break;
			case SIZETYPE_KB:
				fileSizeLong=Double.valueOf(df.format((double) fileS / 1024));
			break;
			case SIZETYPE_MB:
				fileSizeLong=Double.valueOf(df.format((double) fileS / 1048576));
			break;
			case SIZETYPE_GB:
				fileSizeLong=Double.valueOf(df.format((double) fileS / 1073741824));
			break;
			}
		return fileSizeLong;
	}
	
	public boolean detectCacheFileDir() {
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) { 
			if(freeSpaceOnSd() <= 5){
				ViewUtil.popup("亲，SD卡已满，请清理SD卡后，再重试！");
				return false;
			} else{
				checkPath();
				File file = new File("/sdcard/" + patchDefine.getIconFilePath());
				if (!file.exists()) {
					file.mkdirs();
				} 
				return true;
			}
		} else {
			ViewUtil.popup("SD卡不可用！");
			return false;
		}
	}
	
	public boolean detectDownloadFileDir() {
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) { 
			if(freeSpaceOnSd() < 10){
				ViewUtil.popup("亲，SD卡已满，请清理SD卡后，再重试！");
				return false;
			} else {
				checkPath();
				File tmpFile = new File("/sdcard/" + patchDefine.getDownloadPath()); 
				if (!tmpFile.exists()) {
					tmpFile.mkdir();
				}
				return true;
			} 
		} else {
			ViewUtil.popup("SD卡不可用！");
			return false;
		}
	}
	
	public String getImageCachePath(String imageName, String url) {
		String imageDir = Environment.getExternalStorageDirectory().toString() + patchDefine.getIconFilePath();
		String[] names = url.split("\\.");
		return makePath(imageDir, imageName, "." + names[names.length - 1]);
	}
	
	//TODO 检查图片格式 是 jpeg 或者是png
	public String getImageCachePath(String imageName) {
		String imageDir = Environment.getExternalStorageDirectory().toString() + patchDefine.getIconFilePath();
		return makePath(imageDir, imageName, ".jpg");
	}
	
	//TODO 检查图片格式 是 jpeg 或者是png
	public String getImageDownloadPath(String imageName) {
		String imageDir = Environment.getExternalStorageDirectory().toString() + patchDefine.getDownloadPath();
		return makePath(imageDir, imageName, ".jpg");
	}
	
	/**
	 * 创建下载位置
	 * @param imageDir		文件夹位置
	 * @param imageName		文件名称
	 * @param backName		后缀名
	 * @return
	 */
	private String makePath(String imageDir, String imageName, String backName ) {
		File file = new File(imageDir);
		if (!file.exists()) {
			file.mkdirs();
		}
		String imagePath = imageDir + imageName + backName;
		return imagePath;
	}
	
	private void checkPath() {
		if (patchDefine == null) {
			throw new NullPointerException("pathDefine is Undefine. Please extends the PatchDefine class and define path");
		}
	}
	
	/****** 获取SD卡剩余空间 *****/
	private int freeSpaceOnSd() {
		StatFs stat = new StatFs(Environment.getExternalStorageDirectory()
				.getPath());
		double sdFreeMB = ((double) stat.getAvailableBlocks() * (double) stat
				.getBlockSize()) / (1024*1024);
		return (int) sdFreeMB;
	}
	
}
